package com.lagou.niancheng.core.session;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * mapper代理
 *
 * @author 大犬
 * @date 2020/3/27
 */
public class MapperProxy implements InvocationHandler {

    private SqlSession sqlSession;

    public MapperProxy(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 底层都还是去执行JDBC代码 //根据不同情况，来调用selectList或者selectOne
        // 准备参数 1：statementId :sql语句的唯一标识：namespace.id= 接口全限定名.方法名
        // 方法名：findAll
        String methodName = method.getName();
        String className = method.getDeclaringClass().getName();
        String statementId = className + "." + methodName;
        // 准备参数2：params:args
        // 获取被调用方法的返回值类型
        Type genericReturnType = method.getGenericReturnType();
        return sqlSession.executeStatement(genericReturnType, statementId, args);
    }
}
